var publicApi = require('../../script/public.js');
var revenueApi = require('../../script/revenue.js');
const App = getApp();
var config = require('../../script/config.js')
import tool from '../../utils/common.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: config.baseUrl,
    /******** 用户查询 ***********/
    SearchType: '1',
    DeptPart1Show: false,
    DeptPart2Show: false,
    DeptList: [],
    DeptListShow: [],
    BuildingShow: false,
    BuildingList: [],
    BuildingListShow: [],
    METER_NO: '', // 表号
    DeptPart1: '',
    DeptPart1Name: '',
    DeptPart2: '',
    DeptPart2Name: '',
    DoorPlate: '',
    Unit: '',
    searchText: '',
    /******** 用户查询 ***********/

    /******** 查询结果 ***********/
    ReadData1: {
      ConsAddress: '',
      ConsName: '', // 户名
      ConsNo: '', // 户号
      LastReadNumber: null, // 上年读数
      LastReadTime: '',
      ReadNumber: null, // 本年读数
    },
    ReadData2: {
      ConsAddress: '',
      ConsName: '', // 户名
      ConsNo: '', // 户号
      LastReadNumber: null, // 上年读数
      LastReadTime: '',
      ReadNumber: null, // 本年读数
    },
    /******** 查询结果 ***********/

    /******** 图片上传 ***********/
    imgList: [], // 显示的图片列表
    imgFileList: [], // 上传的图片文件列表
    /******** 图片上传 ***********/
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDepts();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /******** 按表号查询 ***********/
  meterNoChange: tool.debounce(function (e) {
    const ev = e[0];
    this.setData({
      METER_NO: ev.detail.value,
    });
    this.SerchUser();
  }, 600),
  /******** 按表号查询 ***********/
  /******** 按区域查询 ***********/
  getDepts() {
    const params = {
      queryParam: {
        DropType: 1,
        Param_0: ''
      },
      pagination: {
        rows: 10000,
        page: 1,
        sidx: "",
        sord: ""
      }
    }
    publicApi.GetDropDownList_Page(params).then(res => {
      if (res.code === 200) {
        this.setData({
          DeptList: res.data.Items,
          DeptListShow: res.data.Items,
        });
      }
    })
  },
  getBuilding() {
    const params = {
      queryParam: {
        DropType: 3,
        Param_0: '',
        Param_1: this.data.DeptPart1,
        Param_2: ""
      },
      pagination: {
        rows: 10000,
        page: 1,
        sidx: "",
        sord: ""
      }
    }
    publicApi.GetDropDownList_Page(params).then(res => {
      if (res.code === 200) {
        this.setData({
          BuildingList: res.data.Items,
          BuildingListShow: res.data.Items,
        });
      }
    })
  },
  SearchTypeChange(e) {
    this.setData({
      SearchType: e.detail.value
    });
  },
  showPopup(e) {
    const popupType = e.currentTarget.dataset.pop;
    if (popupType === 'DeptPart2' && this.data.DeptPart1 === '') {
      wx.showToast({
        title: '请先选择小区',
        icon: 'none'
      });
      return;
    }
    if(popupType === 'DeptPart2'){
      this.getBuilding();
    }
    this.setData({
      [popupType + 'Show']: true
    });
  },
  searchDeptPart1Change: tool.debounce(function (e) {
    const ev = e[0];
    const list = [...this.data.DeptList];
    const newList = list.filter(item => {
      return item.Label.indexOf(ev.detail.value) > -1
    })
    this.setData({
      searchText: ev.detail.value,
      DeptListShow: newList
    });
  }, 600),
  addDeptPart1(e) {
    const dept = e.currentTarget.dataset.info;
    this.setData({
      DeptPart1: dept.Value,
      DeptPart1Name: dept.Label,
      DeptPart2: '',
      DeptPart2Name: '',
      DeptPart1Show: false
    });
    this.getBuilding();
  },
  searchDeptPart2Change: tool.debounce(function (e) {
    const ev = e[0];
    const list = [...this.data.BuildingList];
    const newList = list.filter(item => {
      return item.Label.indexOf(ev.detail.value) > -1
    })
    this.setData({
      searchText: ev.detail.value,
      BuildingListShow: newList
    });
  }, 600),
  addDeptPart2(e) {
    const dept = e.currentTarget.dataset.info;
    this.setData({
      DeptPart2: dept.Value,
      DeptPart2Name: dept.Label,
      DeptPart2Show: false
    });
  },
  deptChange: tool.debounce(function (e) {
    const ev = e[0];
    const type = ev.currentTarget.dataset.type;
    this.setData({
      [type]: ev.detail.value,
    });
    this.SerchUser();
  }, 600),
  leave() {
    this.setData({
      DeptPart1Show: false,
      DeptPart2Show: false,
      searchText: '',
      DeptListShow: [...this.data.DeptList],
      BuildingListShow: []
    });
  },
  SerchUser() {
    this.reset();
    wx.showLoading({
      title: '查询中...',
      mask: true
    });
    let params = {};
    if (this.data.SearchType === '1') {
      params = {
        MeterNo: this.data.METER_NO
      }
    } else {
      params = {
        DeptPart1: this.data.DeptPart1,
        DeptPart2: this.data.DeptPart2,
        HourceNo: this.data.Unit,
        DoorPlate: this.data.DoorPlate
      }
    }
    revenueApi.GetConsMeter(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        const key = 'ReadData' + this.data.SearchType
        this.setData({
          [key]: res.data
        });
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(() => {
      wx.hideLoading();
    })
  },
  /******** 按区域查询 ***********/
  reset() {
    this.setData({
      ReadData: {
        ConsAddress: '',
        ConsName: '',
        ConsNo: '',
        LastReadNumber: null,
        LastReadTime: '',
        ReadNumber: null,
      }
    });
  },
  /************ 图片上传 ************/
  chooseImage: function () {
    if (this.data.imgFileList.length >= 1) {
      wx.showToast({
        title: '最多只能上传5张图片！',
        icon: "none",
        duration: 2000
      })
      return
    }
    const _this = this;
    // 上传图片
    wx.chooseImage({
      count: 1 - this.data.imgFileList.length, //默认9
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.showLoading({
          mask: true,
          title: '上传中...'
        });
        const tempFiles = res.tempFiles;
        _this.uploadOneByOne(tempFiles, 0, 0, 0, tempFiles.length);
      }
    });
  },
  async uploadOneByOne(imgPaths, successUp, failUp, count, length) {
    var that = this;
    const token = wx.getStorageSync(config.storageKey.token)
    const xtoken = wx.getStorageSync(config.storageKey.xtoken)
    // const addWatermarkRes = await that.addWatermark(imgPaths[count].path) //先加水印
    if (imgPaths[count].path) {
      wx.uploadFile({
        url: config.baseUrl + '/api/Upload/Upload',
        method: "POST",
        header: {
          'Authorization': 'Bearer ' + token,
          'X-Authorization': 'Bearer ' + xtoken
        },
        filePath: imgPaths[count].path,
        // filePath: addWatermarkRes,
        name: 'file',
        timeout: 120000, // 超时时间
        success: (resf) => {
          if (resf.statusCode === 200) {
            const resData = JSON.parse(resf.data);
            if (resData && resData.code === 200) {
              successUp++; //成功+1
              const relData = resData.data;
              const file = {
                FileName: relData[0],
                FilePath: relData[0],
                Size: imgPaths[count].size
              }
              that.setData({
                imgList: that.data.imgList.concat(config.baseUrl + '/' + relData[0]),
                imgFileList: that.data.imgFileList.concat(file)
              })
            } else {
              failUp++; //失败+1
            }
          } else {
            failUp++; //失败+1
          }
        },
        fail: function (e) {
          failUp++; //失败+1
        },
        complete: function (e) {
          count++; //下一张
          if (count == length) {
            if (successUp > 0) {
              wx.showToast({
                title: '已上传' + successUp + "张图片",
                icon: 'success',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: "图片上传失败",
                icon: 'error'
              })
            }
          } else {
            that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
          }
        }
      })
    } else {
      failUp++; //失败+1
      count++; //下一张
      if (count != length) {
        that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
      }
    }
  },
  previewImage: function (e) {
    //预览图片
    const that = this;
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: that.data.imgList[index],
      urls: that.data.imgList
    })
  },
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: "提示",
      content: "是否要删除该图片",
      success: (res) => {
        if (res.confirm) {
          const imgList = [...this.data.imgList]
          const imgFileList = [...this.data.imgFileList]
          imgList.splice(index, 1);
          imgFileList.splice(index, 1);
          this.setData({
            imgList: imgList,
            imgFileList: imgFileList
          })
        }
      }
    })
  },
  /************ 图片上传 ************/
  numChange(e) {
    const key = this.data.SearchType === '1' ? 'ReadData1.ReadNumber' : 'ReadData2.ReadNumber'
    this.setData({
      [key]: e.detail.value
    });
  },
  Save() {
    const ReadData = this.data.SearchType === '1' ? this.data.ReadData1 : this.data.ReadData2
    if (ReadData.ConsNo === '') {
      wx.showToast({
        title: '请先查询用户！',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (ReadData.ReadNumber == null) {
      wx.showToast({
        title: '请填写抄表读数！',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: '抄表中...',
      mask: true
    });
    const params = {
      ConsNo: ReadData.ConsNo,
      ReadNumber: ReadData.ReadNumber,
      PicPath: this.data.imgFileList.length > 0 ? this.data.imgFileList[0].FilePath : ''
    }
    revenueApi.SaveMeterData(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 2000
        })
      }
    }).catch(() => {
      wx.hideLoading();
    })
  },
})